<?php
namespace App\Repos;

use App\Models\UserGroupbuy;
use App\Models\ProductGroup;
use App\Models\Order;
use DB;
use Carbon\Carbon;

class UserGroupbuyRepo
{
	public static function  getPages($where=[],$num=10)
	{	   
	  	$list = UserGroupbuy::select(['shop_id','product_id','product_num'])->with('product:id,name,thumb,price')->where($where)->paginate($num); 
	  	return $list;     
	}

	public static function create($data)
	{
		$rs['status'] = true;
		// 如果已经发起此产品的拼团那么直接返回拼团信息
		$where = array_only($data, ['user_id', 'product_group_id']);
		if(array_get($data,'parent_id',0)==0) {
			$where['parent_id'] = 0;	
			$where['status']    = 1;
			$flag  = UserGroupbuy::where($where)->first();
			if($flag) {
				$rs['msg'] = '您已经发起过本商品的拼团';
				return $rs;
			}
		}
		
		

		//团购信息
		$productGroup = ProductGroup::find($data['product_group_id']);
		try {
			DB::beginTransaction();
			if(array_get($data,'parent_id')) {
				
				

				$ugb = UserGroupbuy::find($data['parent_id']);
				if($ugb['user_id'] == $data['user_id']) {
					$rs['msg'] = '不能参与自己发起的拼团活动';
					return $rs;
				}

				if($ugb['status']!=1) {
					$rs['msg'] = '拼团活动已经结束,无法跟团';
					return $rs;
				}
				$data['code']   = $ugb->code;
				$data['end_at'] = $ugb->end_at;
				// 统计人数
				$num = UserGroupbuy::where(['code'=>$ugb->code])->count();
				
				// 统计人数加上本次跟团的人跟团购要求的人数比较
				if( ($num+1)>=$productGroup->group_num ){
					//如果人数够了，修改订单状态为1
					if($ugb->status == 1) {
						Order::where(['group_code'=>$ugb->code])
							->update(['status'=>1]);
					// 修改用户团购表的状态改为100	
					
						UserGroupbuy::where(['code'=>$ugb->code])
									->update(['status'=>100]);	
					}						
					$data['status'] = 100;			
				}

				// 查看自己有没有发起过同款
				
				$had = UserGroupbuy::where($where)->first();
				if($had) {
					$rs['msg'] = '您之前已经生成过此生品的拼团订单，要保留还是取消原来的订单？';
					$rs['data']['group_code']    = $had->code;					
					
				}
				
			} else {
				$data['code'] = str_random(16);
			}
			$data['end_at'] = Carbon::now()->addHours($productGroup->valid_time);
			$flag = UserGroupbuy::create($data);
			DB::commit();			
		} catch (\Exception $e) {
			$rs['status'] = false;
			$rs['msg']    = $e->getMessage();
			DB::rollBack();
			return $rs;
		}
		// 如果是跟单就用父id的code，新发起的就生成code
				
		return $rs;		
	}

	// 参与拼单
	public static function follow($data)
	{

	}

	public static function find($where=[])
	{
		return UserGroupbuy::where($where)
							->orderBy('created_at','desc')
							->first();
	}

	
	
	

	
	
	
}